package com.giggle.nacos.processor;

import com.giggle.common.helper.ReflectHelper;
import com.giggle.nacos.discovery.NacosDiscoveryClient;
import com.giggle.nacos.registry.springcloud.NacosRegistration;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (这里用一句话描述累的作用)
 * @date 2020/8/26 17:48
 */
@Component
public class NacosBeanPostProcessor implements BeanDefinitionRegistryPostProcessor {
    private static final String NACOS_REGISTRATION_BEAN = "nacosRegistration";
    private static final String RIBBON_SERVER_LIST = "ribbonServerList";
    private static final String NACOS_DISCOVERY_CLIENT = "nacosDiscoveryClient";

    public NacosBeanPostProcessor() {
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        Map<String, BeanDefinition> beanDefinitionMap = (Map)ReflectHelper.getFieldValue(beanDefinitionRegistry, "beanDefinitionMap");
        Iterator var3 = beanDefinitionMap.entrySet().iterator();

        while(var3.hasNext()) {
            Map.Entry<String, BeanDefinition> entry = (Map.Entry)var3.next();
            BeanDefinition beanDefinition = (BeanDefinition)entry.getValue();
            if (NACOS_REGISTRATION_BEAN.equals(entry.getKey())) {
                beanDefinitionRegistry.removeBeanDefinition((String)entry.getKey());
                beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(NacosRegistration.class).getBeanDefinition();
                beanDefinitionRegistry.registerBeanDefinition((String)entry.getKey(), (BeanDefinition)beanDefinition);
            }

            if (NACOS_DISCOVERY_CLIENT.equals(entry.getKey())) {
                beanDefinitionRegistry.removeBeanDefinition((String)entry.getKey());
                beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(NacosDiscoveryClient.class).getBeanDefinition();
                beanDefinitionRegistry.registerBeanDefinition((String)entry.getKey(), (BeanDefinition)beanDefinition);
            }

            if ("referenceAnnotationBeanPostProcessor".equals(entry.getKey())) {
                System.out.println(((BeanDefinition)beanDefinition).getBeanClassName());
            }
        }

    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }
}
